<template>
  <div class="user-setting-container">
    <el-card shadow="hover">
      <div slot="header" class="card-header">
        <h3>博客设置编辑</h3>
      </div>

      <!-- 加载状态 -->
      <el-loading v-if="loading" text="加载设置数据中..." fullscreen></el-loading>

      <!-- 编辑表单（默认开启编辑，验证仅需非空） -->
      <el-form v-else :model="settingForm" label-width="120px" class="setting-form" ref="settingFormRef">
        <el-form-item label="博客标题" required :rules="[{ required: true, message: '博客标题不能为空', trigger: 'blur' }]">
          <el-input v-model="settingForm.blogTitle" placeholder="请输入博客标题" style="width: 60%;"></el-input>
        </el-form-item>
        <el-form-item label="博客描述" required :rules="[{ required: true, message: '博客描述不能为空', trigger: 'blur' }]">
          <el-input v-model="settingForm.blogDesc" type="textarea" rows="3" placeholder="请输入博客描述"
            style="width: 60%;"></el-input>
        </el-form-item>
        <el-form-item label="博主名称" required :rules="[{ required: true, message: '博主名称不能为空', trigger: 'blur' }]">
          <el-input v-model="settingForm.authorName" placeholder="请输入博主名称" style="width: 60%;"></el-input>
        </el-form-item>
        <el-form-item label="博主头像">
          <el-upload action="#" :on-success="handleAvatarUpload" :file-list="avatarFileList" accept="image/*"
            list-type="picture-card" style="margin-bottom: 10px;">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-img :src="settingForm.authorAvatar || defaultAvatar" fit="cover"
            style="width: 120px; height: 120px;"></el-img>
        </el-form-item>
        <el-form-item label="联系邮箱" required :rules="[{ required: true, message: '联系邮箱不能为空', trigger: 'blur' }]">
          <el-input v-model="settingForm.contactEmail" placeholder="请输入联系邮箱" style="width: 60%;"></el-input>
        </el-form-item>
        <el-form-item label="最后更新">
          <el-input v-model="settingForm.updateTime" placeholder="暂无更新记录" disabled></el-input>
        </el-form-item>
      </el-form>

      <!-- 唯一操作按钮：确认更改 -->
      <div class="form-footer" style="margin-top: 30px; text-align: right;">
        <el-button type="primary" @click="submitSetting" :loading="submitLoading">
          确认更改
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'UserSetting',
  data() {
    return {
      loading: false,
      submitLoading: false, // 提交按钮加载态
      defaultAvatar: 'https://tva1.sinaimg.cn/crop.0.0.1080.1080.180/006y8mN6ly1g6e2tdgve1j30u00u0n0j.jpg',
      avatarFileList: [], // 头像上传文件列表
      // 设置表单（字段与接口返回匹配）
      settingForm: {
        blogTitle: '',
        blogDesc: '',
        authorName: '',
        authorAvatar: '',
        contactEmail: '',
        updateTime: '',
        id: '' // 隐藏字段：设置ID（接口返回后赋值，用于修改时传参）
      }
    }
  },
  mounted() {
    this.getSettingDetail(); // 页面加载直接获取设置数据，渲染为编辑态
  },
  methods: {
    // 获取设置详情（加载初始编辑数据）
    async getSettingDetail() {
      this.loading = true;
      try {
        const res = await this.$axios.post(
          'http://47.104.167.34:9110/api/admin/blog/setting/detail'
        );
        if (res.data.success) {
          const settingData = res.data.data;
          // 赋值表单数据，格式化时间
          this.settingForm = {
            ...settingData,
            updateTime: this.formatTime(settingData.updateTime)
          };
          // 若有头像，初始化上传文件列表
          if (settingData.authorAvatar) {
            this.avatarFileList = [{ url: settingData.authorAvatar }];
          }
        } else {
          this.$message.error(`加载失败：${res.data.message || '未知错误'}`);
        }
      } catch (err) {
        this.$message.error('接口请求异常，请稍后重试');
        console.error('SettingDetail request error:', err);
      } finally {
        this.loading = false;
      }
    },

    // 头像上传成功处理（实际项目需替换为真实上传接口）
    handleAvatarUpload(response, file) {
      // 假设上传接口返回头像地址，赋值给表单
      console.log(file);
      
      if (response?.success) {
        this.settingForm.authorAvatar = response.data;
        this.avatarFileList = [{ url: response.data }];
      } else {
        this.$message.error('头像上传失败，请重试');
        this.avatarFileList = [];
      }
    },

    // 时间格式化（YYYY-MM-DD HH:mm:ss）
    formatTime(timestamp) {
      if (!timestamp) return '暂无记录';
      const date = new Date(timestamp);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    },

    // 提交修改（唯一操作：确认更改）
    async submitSetting() {
      // 表单校验（仅验证非空）
      const formRef = this.$refs.settingFormRef;
      if (!formRef) return;
      try {
        await formRef.validate(); // 触发表单非空校验
        this.submitLoading = true;

        // 调用修改接口（文档未提供，按常规命名拼接）
        const res = await this.$axios.post(
          'http://47.104.167.34:9110/api/admin/blog/setting/update',
          this.settingForm // 携带设置ID和修改后的数据
        );

        if (res.data.success) {
          this.$message.success('设置修改成功！');
          // 重新加载最新数据（更新"最后更新"时间）
          this.getSettingDetail();
        } else {
          this.$message.error(`修改失败：${res.data.message || '未知错误'}`);
        }
      } catch (err) {
        // 表单校验失败（仅非空）或接口异常
        if (err.name === 'ValidationError') {
          this.$message.warning('请完善所有必填项');
        } else {
          this.$message.error('提交异常，请稍后重试');
          console.error('SettingUpdate request error:', err);
        }
      } finally {
        this.submitLoading = false;
      }
    }
  }
}
</script>

<style scoped>
.user-setting-container {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
}

.setting-form {
  margin-top: 20px;
}

.form-footer {
  margin-top: 20px;
}

/* 调整上传组件样式 */
.el-upload--picture-card {
  width: 120px;
  height: 120px;
}
</style>